#include "splashscreen.h"
#include <wx/dcclient.h>
#include <wx/dcmemory.h>
#include <wx/dcscreen.h>
#include "configmanager.h"
#include "pluginmanager.h"
#include "prep.h"

namespace {
  int cbSplashScreen_timer_id = wxNewId();
}

BEGIN_EVENT_TABLE( M_Code_SplashScreen, wxFrame )
  EVT_PAINT( M_Code_SplashScreen::OnPaint )
  EVT_TIMER( cbSplashScreen_timer_id, M_Code_SplashScreen::OnTimer )
  EVT_CLOSE( M_Code_SplashScreen::OnCloseWindow )
  EVT_CHAR( M_Code_SplashScreen::OnChar )
  EVT_MOUSE_EVENTS( M_Code_SplashScreen::OnMouseEvent )
END_EVENT_TABLE()

void M_Code_SplashScreen::DrawReleaseInfo( wxDC  &dc ) {
  wxFont largeFont( 15, wxFONTFAMILY_SWISS, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_BOLD );
  wxFont smallFont( 10, wxFONTFAMILY_SWISS, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_BOLD );
  int text_center = 450;
  int x_offset = text_center;
  int y = 220;
  dc.SetTextForeground( *wxBLACK );
  x_offset = text_center  / 2;
  dc.SetFont( largeFont );
  if( PluginManager::GetSafeMode() ) {
    wxCoord sm_width, sm_height, sm_descend;
    dc.GetTextExtent( _T( "SAFE MODE" ), &sm_width, &sm_height, &sm_descend, nullptr, &smallFont );
    dc.SetFont( smallFont );
    dc.SetTextForeground( *wxRED );
    x_offset = text_center - ( sm_width ) / 2;
    dc.DrawText( _T( "SAFE MODE" ), x_offset, ( y  - sm_height + sm_descend  + 10 ) );
    dc.SetTextForeground( *wxBLACK );
  }
}

void M_Code_SplashScreen::DoPaint( wxDC & ) {
  wxPaintDC dc( this );
  dc.DrawBitmap( m_label, 0, 0, false );
  DrawReleaseInfo( dc );
}

void M_Code_SplashScreen::OnPaint( wxPaintEvent & ) {
  wxPaintDC paint_dc( this );
  DoPaint( paint_dc );
}

void M_Code_SplashScreen::OnTimer( wxTimerEvent & ) {
  Close( true );
}

void M_Code_SplashScreen::OnCloseWindow( wxCloseEvent & ) {
  m_timer.Stop();
  Hide();
}

void M_Code_SplashScreen::OnChar( wxKeyEvent & ) {
  Close( true );
}

void M_Code_SplashScreen::OnMouseEvent( wxMouseEvent &event ) {
  if( event.LeftDown() || event.RightDown() ) {
    Close( true );
  }
}

M_Code_SplashScreen::M_Code_SplashScreen( wxBitmap &label, long timeout, wxWindow *parent, wxWindowID id, long style )
  : wxFrame( parent, id, wxEmptyString, wxPoint( 0, 0 ), wxSize( 0, 0 ), style ),
    m_timer( this, cbSplashScreen_timer_id ) {
  int w = label.GetWidth();
  int h = label.GetHeight();
  SetClientSize( w, h );
  CentreOnScreen();
  wxScreenDC screen_dc;
  wxMemoryDC label_dc;
  int x = GetPosition().x;
  int y = GetPosition().y;
  m_label.Create( w, h );
  label_dc.SelectObject( m_label );
  label_dc.Blit( 0, 0, w, h, &screen_dc, x, y );
  label_dc.DrawBitmap( label, 0, 0, true );
  label_dc.SelectObject( wxNullBitmap );
  Show( true );
  SetThemeEnabled( false );
  SetBackgroundStyle( wxBG_STYLE_CUSTOM );
  wxYieldIfNeeded();
  if( timeout != -1 ) {
    m_timer.Start( timeout, true );
  }
}

M_Code_SplashScreen::~M_Code_SplashScreen() {
  m_timer.Stop();
}
